$(function() {
	var basePath=$('#basePath').val();
	$('.tags').on('click','.show-tag',function(){
		if(!isLogin()){
			openLogin();
			return ;
		}
		$('#tag-bag-model').modal('show');
		$('#temp-data').attr('name',$(this).html());
		$('#temp-data').attr('idn',$(this).attr('id'));
	});
	/*$('.show-tag').click(function(){
		if(!isLogin()){
			openLogin();
			return ;
		}
		$('#tag-bag-model').modal('show');
		$('#temp-data').attr('name',$(this).html());
		$('#temp-data').attr('idn',$(this).attr('id'));
	});*/
	$('.link-bag').click(function(){
		var typeID=$(this).attr('id');
		typeID='b'+typeID.substring(3, typeID.length);
		var ready=$('#'+typeID).find('.bg-tags').find('a');
		var id=$('#temp-data').attr('idn');
		for(var i=0;i<ready.length;i++){
			if($(ready[i]).attr('id')==('f'+id)){
				$('#tag-bag-model').modal('hide');
				return;
			}
		}
		var name=$('#temp-data').attr('name');
		appendHtml(name,typeID,id);
		$('#tag-bag-model').modal('hide');
	});
	$('#logout-btn').click(function(){
		$("#lgmk2,.lgout-box").show();
	});
	//根据标签生成人数
	$(".confirm-tags").click(function(){
		if(!isLogin()){
			 openLogin();
			return ;
		}
		var tags= getTags(this);
		var types='';
		tags.each(function(){
			types+=$(this).attr('id')+',';
		});
		if(types.length>0){
			types=types.substring(0, types.length-1);
		}else{
			createTip(this);
			return;
		}
		$.ajax({
	         type: "GET",
	         url: basePath+'/api/v1/getCreditCount' ,
	         data: {
	        	 types:types
	        	 },
	         async:false,
	         success: function(data){
	        	$("#result-count").html("目标人数为："+data+"人<br/>签购单营销预计可触达人群："+data+"人<br/>短信营销预计可触达人群："+data+"人");
	         }
	     });
	});
	//配置广告
	$('.config-adv').click(function(){
		if(!isLogin()){
			 openLogin();
			return ;
		}
		var types=[];
		var tags= getTags(this);
		tags.each(function(){
			types.push('{id:'+$(this).attr('id')+'}');
		});
		if(types.length==0){
			createTip(this);
			return;
		}
		configureAdv("admin","admin",types);
	});
	//登入
	$('#lgbtn').click(function(){
		var username=$("#username").val();
		var password=$("#password").val();
		var verifyCode=$("#verifyCode").val();
		if(username==''){
			 $('#err-mes').html("用户名不能为空");
			return;
		}
		if(password==''){
			 $('#err-mes').html("密码不能为空");
			return;
		}
		if(verifyCode==''){
			 $('#err-mes').html("验证码不能为空");
			return;
		}
		 $.ajax({
             type: "POST",
             url: basePath+'/view/login' ,
             data: {
            	 username:username,
            	 password:password,
            	 verifyCode:verifyCode
            	 },
             success: function(data){
                         if(data==1){
                        	 $('#err-mes').html("账号或者密码错误");
                         }else if(data==2){
                        	 $('#err-mes').html('验证码错误');
                         }else if(data==0){
                        	 $('#err-mes').html('登入成功');
                        	 $(this).find('td').css("color","#777777");
                        	 window.location.href=window.location.href; 
                         }else if(data==3){
                        	 $('#err-mes').html('验证码过期');
                         }
                      }
         });
	});
	//搜索
	$("#search-btn").click(function(){
		$('.search-data').remove();
		var val=$('#search-input').val();
		if(val==''){
			$('#accordion').show();
		}else{
			$('#accordion').hide();
			$.ajax({
		         type: "GET",
		         dataType:"json",
		         url: basePath+'/api/v1/search' ,
		         data: {
		        	 param:val
		        	 },
		         async:false,
		         success: function(data){
		        	if(data.length>0){
		        		var html='<ul class="submenu search-data" style="overflow: hidden; display: block;">';
		        		for(var i=0;i<data.length;i++){
		        			html+='<li><div class="show-tag" flag="type1" id="'+data[i].id+'">'+data[i].name+'</div></li>';
		        		}
		        		html+='</ul>';
		        		$('.tags').append(html);
		        	}else{
		        		$('#accordion').show();
		        	}
		         }
		     });
		}
	});
});
//登出
function logout(){
	var basePath=$('#basePath').val();
	 $.ajax({
        type: "POST",
        url: basePath+'/view/logout',
        async: false
    });
	 window.location.href=window.location.href; 
}
//选择标 签生成
function appendHtml(name,type,id){
	var cHtml='';
	cHtml+='<div class="bg-tags">'+name+'<a href="javascript:void(0)" name='+name+' onclick=reTag(this) id="f'+id+'"><i class="icon-remove">×</i></a></div>';
	$('#'+type).append(cHtml);
}
//删除标签
function reTag(obj){
    var id=$(obj).attr('id');
    id=id.substring(1,id.length);
	$(obj).parent().remove();
	$('#'+id).removeAttr('click');
} 
//判断是否登入
function isLogin(){
	var basePath=$('#basePath').val();
	var flag=false;
	 $.ajax({
         type: "POST",
         url: basePath+'/view/checkLogin' ,
         data: {
        	 },
         async:false,
         success: function(data){
        	 if(data=="ok")
        	 flag=true;
         }
     });
	 return flag;
}
////取消退出
function acancle(){
     $('#lgmk2,.lgout-box').hide();
}
//确定退出
function aconfirm(){
	logout();
}
/* ----------------------------------------------------------------------------------------------------------------- */
//打开登入框
function openLogin() {
	$("#lgmk2,#lgkuang2,#lgct").show();
}
//关闭登入框
function closeLogin() {
	$("#lgError").hide();
	$("#userAcntn").val("");
	$("#userPwdn").val("");
	$("#lgmk2,#lgkuang2,#lgct,#lgife,#xlgct").hide();
	$("#lgife").attr("src", "");
} 
//重新验证码
function reCheckcode(img) {
	var basePath=$('#basePath').val();
	img.src = basePath + "/view/drawCheckCode?" + Math.random();
}
/*=====================================配置广告============================================================================*/
function configureAdv(username,password,tags) {
    var data = { 
    		username:username,
    		password:password,
    		tags:JSON.stringify(tags),//标签组
    		time:dateFormater(new Date()),//时间戳
    		uuid:UUID.prototype.createUUID ()
    };
    saveConfig_Adv(data);
}
//生成tip
function createTip(obj){
	var html='<div class="rc_box1"><div class="rc_box2"><div class="rc_box3">请选择标签！</div></div><div class="ov1"></div></div>';
	$(obj).before(html);
	setTimeout(function () {
		$(obj).parent().find('.rc_box1').fadeOut().remove();
	},1000);
}
//获得标签组
function getTags(obj){
	return $(obj).parent().parent().prev().find('a');
}
//返回 yy-MM-dd h:m:s
function dateFormater(date){
	return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
}
//存储广告配置
function saveConfig_Adv(data,fun){
	var basePath=$('#basePath').val();
	 $.ajax({
         type: "POST",
         url: basePath+'/view/saveConfigAdv' ,
         data:data,
         async:false,
         success: function(data){
        	/* if(data=="ok"&&fun!=null)
        	     fun();*/
         }
     });
}
//跳转至广告配置页面
function directAdvConPage(data){
	var strUrl = "https://";
	 var myForm = document.createElement("form");
	    myForm.method = "post";
	    myForm.action = strUrl;

	    var myInput = document.createElement("input");

	    myInput.setAttribute("name", "data");

	    myInput.setAttribute("value",data);

	    myForm.appendChild(myInput);

	    document.body.appendChild(myForm);

	    myForm.submit();
	    
	    document.body.removeChild(myForm);
}